//
//  ST_RechargeViewController.swift
//  btvideo
//
//  Created by mac on 2020/7/1.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SnapKit
import SwifterSwift
import MBProgressHUD
import SwiftyAttributes
import SwiftyUserDefaults

class ST_RechargeViewController: ST_BTLightBarViewController {

    deinit {
        
        print("充值页面释放")
        
        NotificationCenter.default.removeObserver(self)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        ST_BTGlobalDataCenter.shared.payMenuPage(paramValue: "页面曝光")
        
        self.title_nav_btn.setTitleForAllStates("甜心币")
        
        right_nav_btn.setTitleForAllStates("支付帮助")
        right_nav_btn.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular)
        right_nav_btn.setTitleColorForAllStates(UIColor.init(hex: 0x333333)!)
        right_nav_btn.snp.remakeConstraints { (make) in
            make.right.equalTo(own_navigation_bar).offset(-14)
            make.bottom.equalTo(own_navigation_bar)
            make.height.equalTo(44)
        }
        
        
        right_nav_btn.isHidden = false
        
        
         
        
        self.view.addSubview(tableView)
        tableView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.init(top: statusBarHeight+44, left: 0, bottom: 0, right: 0))
        }
        
        
        self.refresh_coin_handle()
        
        NotificationCenter.default.addObserver(self, selector: #selector(refresh_coin_handle), name: Notification.Name.modifyCoin, object: nil)
        
        JVrequest(PH.getAppleCoinPriceApi, success: { (json) in

            var array = [ST_RechargeSweetCoinCellModel]()
            
            if let list = [ST_RechargeSweetCoinCellModel].deserialize(from: json["data"]["list"].rawString() ?? "") as? [ST_RechargeSweetCoinCellModel]{
                
                
                for (idx,item) in list.enumerated() {
                    
                    item.setUpData(idx: idx)
                    
                    array.append(item)
                }
            }
            
            self.data_array = array
            self.tableView.reloadData()
            
        }) { (code, err) in
            
            
            self.toast(text: err)
        }
        
    }
    

// MARK: - Properties
    fileprivate lazy var tableView:UITableView = {
        
        let control = UITableView.init(frame: CGRect.zero, style: UITableView.Style.plain)
        
        control.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: BTSafeAreaBottom + 30 , right: 0)
        
        control.delegate = self
        control.dataSource = self
        
        control.showsVerticalScrollIndicator = false
        control.showsHorizontalScrollIndicator = false
        
        
        control.register(cellWithClass: ST_RechargeSweetCoinCell.self)
        control.register(cellWithClass: ST_RechargeSweetCoinCenterCell.self)
        
        
        control.separatorStyle = .none
        
        control.backgroundColor = Color.init(hex: 0xF5F8FA)
        
        if #available(iOS 11.0, *) {
            control.contentInsetAdjustmentBehavior = .never
        }
        
        control.tableHeaderView = self.headerView
        
        control.tableFooterView = self.footerView
        
        return control
    }()

    
    fileprivate lazy var headerView:ST_RechargeSweetCoinHeader = {
        let control = ST_RechargeSweetCoinHeader.init(frame: CGRect.init(x: 0, y: 0, width: ScreenWidth, height: ST_RechargeSweetCoinHeader.height))
        return control
    }()
    
    
    fileprivate lazy var footerView:UIButton = {
        
        let control = UIButton.init(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: 60))
        
        let str = "充值代表阅读并同意".withAttributes([.font(.systemFont(ofSize: 14, weight: .regular)),.textColor(UIColor(hex: 0x8D8D8D)!)])
        
        str.append("《用户充值协议》".withAttributes([.font(.systemFont(ofSize: 14, weight: .regular)),.textColor(UIColor(hex: 0x3598FF)!)]))
                   
       control.setAttributedTitle(str, for: .normal)

        control.addTarget(self, action: #selector(jump_to_recharge_protocol_page), for: .touchUpInside)
        return control
    }()
    
    fileprivate lazy var data_array = [ST_RechargeSweetCoinCellModel]()
    
    @objc func refresh_coin_handle(){
        
        guard let coin = ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sweet_coin else {
            
            self.headerView.coin = 0
            return
        }
        
        self.headerView.coin = coin.int
        
    }
    
    override func right_click() {
        
        if Defaults[.isPanda]{
            
            
            guard let url = URL(string: PH.helpPayHtml.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)) else { return  }
            
            let vc = ST_RegistStepHelperController()
            
            vc.url = url
            
            vc.hiddenfeedback = true
            
            GlobalPresent(toController: vc)
            
        }else{
            
            GlobalPresent(toController: UINavigationController.create_hiding_bar_navigation_controller(rootViewController: ST_DesignDAController()))
            
        }
        
    }
    
}

extension ST_RechargeViewController:UITableViewDelegate,UITableViewDataSource{
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data_array.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        var cell:ST_RechargeSweetCoinCell!
        
        let model = data_array[indexPath.row]
        
        if model.thrift.count > 1{
            cell = tableView.dequeueReusableCell(withClass: ST_RechargeSweetCoinCell.self, for: indexPath)
        }else{
            cell = tableView.dequeueReusableCell(withClass: ST_RechargeSweetCoinCenterCell.self, for: indexPath)
        }
        
        cell.model = model
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 90+10
    }
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        guard let item_model = data_array[safe:indexPath.row]  else{return}
         
        let str = item_model.descr+item_model.original_price.int.string+"元"+item_model.ename
        
        ST_BTGlobalDataCenter.shared.payMenuPage(paramValue: str)
        
        ST_MaidWayManager.shared.doWay(id: item_model.id.string, delegate: self)
        
    }
    
    @objc private func jump_to_recharge_protocol_page(){
        
        let vc = ST_BTWebViewController()
        
        vc.urlStr = PH.userRechargeProtocolURL
        
        vc.titleStr = "充值协议"
        
        navigationController?.pushViewController(vc, animated: true)
        
    }
    
}


extension ST_RechargeViewController:ST_TIANPaymentTransactionStateDelegate{
            
     func transaction_succeed(){
         
         
         let vc = BTVerticalAlertViewController.createRechargeSuccessAlert()
         
         
         vc.confirm_closure = {
             
             self.goback_previous_controller()
             
         }
         
         GlobalPresent(toController: vc)
        
        
     }
    
}




//MARK: - static Method
extension ST_RechargeViewController{
    
    static func toast(content:String? = nil){
        
        /// 没有买过 首冲
        if let f = ST_LaunchChargeWidget.shared.first_recharge_paid , f == false{
            
            ST_LaunchChargeWidget.shared.push_first_charge()
            
        }else{
            
            
            let vc = ST_ShortcutRechargeController()
            
            vc.overCurrentContext = true
            
            vc.over_current_context_alpha = "0.4"
            
            GlobalPresent(toController: vc)
            
        }
    }
    
}

